<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加新任务"
    width="600px"
    :close-on-click-modal="false"
    class="add-task-dialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="task-form"
    >
      <el-form-item label="任务名称" prop="skillName">
        <div class="task-name-container">
          <div class="input-group">
            <el-autocomplete
              v-model="formData.skillName"
              :fetch-suggestions="querySearch"
              placeholder="请输入任务名称"
              class="task-name-input"
              :trigger-on-focus="true"
              @select="handleSelect"
            />
            <div class="template-group">
              <el-select
                v-model="selectedTemplate"
                placeholder="选择模板(可选)"
                class="template-select"
                @change="handleTemplateChange"
              >
                <template #prefix>
                  <el-icon><Document /></el-icon>
                </template>
                <el-option
                  v-for="template in taskTemplates"
                  :key="template.id"
                  :label="template.name"
                  :value="template.id"
                >
                  <span class="template-option">
                    <el-icon><Document /></el-icon>
                    {{ template.name }}
                  </span>
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="任务描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入任务描述"
        />
      </el-form-item>

      <el-form-item label="任务阶段">
        <div class="stages-container">
          <div
            v-for="(stage, index) in formData.stages"
            :key="index"
            class="stage-item"
          >
            <div class="stage-header">
              <el-input
                v-model="stage.name"
                placeholder="阶段名称"
                class="stage-name"
              />
              <el-button
                type="danger"
                circle
                @click="removeStage(index)"
                :disabled="formData.stages.length === 1"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>

            <div class="nodes-container">
              <div
                v-for="(node, nodeIndex) in stage.nodes"
                :key="nodeIndex"
                class="node-item"
              >
                <el-input
                  v-model="node.name"
                  placeholder="节点名称"
                  class="node-name"
                />
                <el-button
                  type="danger"
                  circle
                  @click="removeNode(stage, nodeIndex)"
                  :disabled="stage.nodes.length === 1"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
              <el-button
                type="primary"
                plain
                @click="addNode(stage)"
                class="add-node-btn"
              >
                <el-icon><Plus /></el-icon>
                添加节点
              </el-button>
            </div>
          </div>

          <el-button
            type="primary"
            plain
            @click="addStage"
            class="add-stage-btn"
          >
            <el-icon><Plus /></el-icon>
            添加阶段
          </el-button>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确认添加
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { Delete, Plus, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { createSkill } from '@/api/skill'
import { getModelList } from '@/api/model'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const dialogVisible = ref(props.modelValue)
const formRef = ref(null)
const submitting = ref(false)

const taskTypes = [
  '理论学习/',
  '实践开发/',
  '专项训练/',
  '社会生活/'
]

// 任务模板数据
const taskTemplates = ref([])
const loading = ref(false)

// 获取模板列表
const fetchTemplates = async () => {
  try {
    loading.value = true
    const response = await getModelList({
      current: 1,
      size: 100
    })
    // 处理返回的数据，将 modelData 解析为对象
    taskTemplates.value = response.data.data.records.map(item => ({
      id: item.id,
      name: item.modelName,
      template: JSON.parse(item.modelData)
    }))
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取模板列表
onMounted(() => {
  fetchTemplates()
})

const formData = reactive({
  skillName: '',
  description: '',
  stages: [
    {
      name: '',
      nodes: [{ name: '' }]
    }
  ]
})

const rules = {
  skillName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

const querySearch = (queryString, cb) => {
  const results = queryString
    ? taskTypes.filter(type => type.toLowerCase().includes(queryString.toLowerCase()))
    : taskTypes
  cb(results.map(type => ({ value: type })))
}

const handleSelect = (item) => {
  formData.skillName = item.value
}

const selectedTemplate = ref('')

const handleTemplateChange = (templateId) => {
  const template = taskTemplates.value.find(t => t.id === templateId)
  if (template) {
    formData.skillName = template.template.skillName
    formData.description = template.template.description
    formData.stages = JSON.parse(JSON.stringify(template.template.stages))
  }
}

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    fetchTemplates()
  }
})

watch(() => dialogVisible.value, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    resetForm()
  }
})

// 方法
const addStage = () => {
  formData.stages.push({
    name: '',
    nodes: [{ name: '' }]
  })
}

const removeStage = (index) => {
  formData.stages.splice(index, 1)
}

const addNode = (stage) => {
  stage.nodes.push({ name: '' })
}

const removeNode = (stage, index) => {
  stage.nodes.splice(index, 1)
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.skillName = ''
  formData.description = ''
  formData.stages = [
    {
      name: '',
      nodes: [{ name: '' }]
    }
  ]
  selectedTemplate.value = ''
}

const handleCancel = () => {
  dialogVisible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    // 验证阶段和节点
    for (const stage of formData.stages) {
      if (!stage.name.trim()) {
        ElMessage.warning('请填写所有阶段名称')
        return
      }
      for (const node of stage.nodes) {
        if (!node.name.trim()) {
          ElMessage.warning('请填写所有节点名称')
          return
        }
      }
    }

    submitting.value = true
    
    const taskData = {
      ...formData,
      skillName: formData.skillName,
      stageVos: formData.stages,
      stages: JSON.stringify(formData.stages)
    }
    
    await createSkill(taskData)
    ElMessage.success('任务创建成功')
    emit('success')
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.add-task-dialog :deep(.el-dialog__body) {
  padding-top: 20px;
}

.task-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 20px;
}

.stages-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stage-item {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e4e7ed;
}

.stage-header {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #dcdfe6;
}

.stage-name {
  flex: 1;
}

.stage-name :deep(.el-input__wrapper) {
  background-color: #fff;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.stage-name :deep(.el-input__inner) {
  font-weight: 500;
  font-size: 15px;
}

.nodes-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-left: 12px;
}

.node-item {
  display: flex;
  gap: 12px;
}

.node-name {
  flex: 1;
}

.node-name :deep(.el-input__wrapper) {
  background-color: #fafafa;
}

.node-name :deep(.el-input__inner) {
  font-size: 14px;
  color: #606266;
}

.add-node-btn {
  margin-left: 0;
  width: 100%;
}

.add-stage-btn {
  width: 100%;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .add-task-dialog :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 auto;
  }

  .task-form {
    padding-right: 0;
  }

  .stage-item {
    padding: 12px;
  }

  .nodes-container {
    padding-left: 8px;
  }

  .add-node-btn {
    margin-left: 0;
    width: 100%;
  }

  .task-name-input {
    flex-direction: column;
    gap: 8px;
  }

  .task-type-select {
    width: 100%;
  }
}

.task-name-container {
  width: 100%;
}

.input-group {
  display: flex;
  gap: 16px;
  align-items: center;
}

.task-name-input {
  flex: 1;
}

.template-group {
  width: 180px;
}

.template-select {
  width: 100%;
}

.template-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-option .el-icon {
  font-size: 16px;
  color: #909399;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .input-group {
    flex-direction: column;
    gap: 12px;
  }

  .task-name-input,
  .template-group {
    width: 100%;
  }
}
</style> 